package pl.polsl.mmm.projectcomm;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;

import pl.polsl.mmm.projectcomm.util.bluetooth.ConnectThread;
import pl.polsl.mmm.projectcomm.util.bluetooth.ConnectedThread;


public class ClientActivity extends Activity {

    BluetoothAdapter mBluetoothAdapter;
    final int REQUEST_ENABLE_BT = 1010;
    TextView receivedText;
    Spinner deviceSpinner = null;
    ClientActivity me;

    // Wyświetlenie tekstu odpowiedzi od serwera
    private final Handler handler = new Handler() {

        public void handleMessage(Message msg) {

            String response = msg.getData().getString("message");

            if ((null != response)) {

                receivedText.setText(response);
//                Toast.makeText(getBaseContext(), "Server Response: " + response,Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client);

        deviceSpinner = (Spinner)findViewById(R.id.deviceSpinner);
        deviceSpinner.setEnabled(false);
        receivedText = (TextView)findViewById(R.id.receivedText);
        me = this;


        try {

            // Pobranie adaptera bluetooth
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

            // Sprawdzenie, czy adapter bluetooth istnieje
            if (mBluetoothAdapter == null) {
                throw new RuntimeException("No bluetooth adapter");
            }

            // Sprawdzenie, czy bluetooth jest włączone
            if (!mBluetoothAdapter.isEnabled()) {
                // Prośba o włączenie bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
                this.finish();
            }

            if(!mBluetoothAdapter.isEnabled())
                this.finish();

            // Pobranie listy sparowanych urzadzeń
            final Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            ArrayList<String> deviceArray = new ArrayList<String>();


            // Wyświetlenie listy urzadzeń do wyboru
            if (pairedDevices.size() > 0) {

                for (BluetoothDevice device : pairedDevices) {
                    deviceArray.add(device.getName() + ' ' + device.getAddress());
                }

                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, deviceArray);
                deviceSpinner.setAdapter(arrayAdapter);

                deviceSpinner.setEnabled(true);

            }

            // Dodanie listenera
            deviceSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                    // Po wybraniu urządzenia jest ono znajdowane wg nazwy
                    String selectedDeviceName = (String) adapterView.getItemAtPosition(i);
                    BluetoothDevice selectedDevice = null;

                    for (BluetoothDevice device : pairedDevices) {
                        if (selectedDeviceName.equals(device.getName() + ' ' + device.getAddress())) {
                            selectedDevice = device;
                            break;
                        }
                    }

                    // Jeśli znaleziono urzadzenie - następuje próba połączenia
                    if (selectedDevice != null) {
                        ConnectThread connectThread = new ConnectThread(me, mBluetoothAdapter, selectedDevice, handler);
                        connectThread.start();
                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });

        } catch (Exception e) {
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.client, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
